import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // 浏览器顶部的进度条
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

// const whiteList = ['/login', '/auth-redirect', '/bind', '/register']
const whiteList = ['/login'] // 白名单
// 黑名单
const displayList = [
  // '/index',
  '/system/role',
  '/system/menu',
  '/system/dept',
  'system/post',
  'system/dict',
  '/system/config',
  '/system/notice',
  '/system/log/operlog',
  '/system/log/logininfor',
  '/system/log/logininfor',
  '/monitor/online',
  '/monitor/job',
  '/monitor/druid',
  '/monitor/server',
  '/monitor/cache',
  '/user/profile'
  // '/equipment/track',
  // '/parmConfig'
]
// 全局前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  // console.log()
  // for (let i = 0; i < store.state.permission.topbarRouters.length; i++) {
  //   console.log(
  //     store.state.permission.topbarRouters[i].meta.title.indexOf('节目管理')
  //   )
  // }
  // 判断有没有token
  if (getToken()) {
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' }) // 有token避免用户手动输入登录页跳转到首页
      NProgress.done()
      return
    } else {
      /* has token roles字段没数据 */
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch('GetInfo')
          .then(() => {
            store.dispatch('GenerateRoutes').then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
          })
          .catch(() => {
            // store.dispatch('LogOut').then(() => {
            //   location.href = window.location.pathname // 获取当前窗口的路径
            // })
          })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // 不在登录白名单
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})
// 全局后置钩子
router.afterEach((to, from) => {
  // part use dept components
  for (let i = 0; i < displayList.length; i++) {
    if (to.path.includes(displayList[i])) {
      store.commit('tree/SET_DISPLAY', false)
      NProgress.done()
      return
    } else {
      store.commit('tree/SET_DISPLAY', true)
      NProgress.done()
    }
  }
})
